package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.model.ListPartsRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author wangyc
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTDAClient;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        //1.从物联网平获取产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = ioTDAClient.listProducts(request);
        List<ProductSummary> products = response.getProducts();

        //2.将产品列表数据存储到Redis缓存中
        redisTemplate.opsForValue().set(CacheConstants.DEVICE_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        //从缓存中获取产品列表数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.DEVICE_PRODUCT_LIST);

        //如果查询不到，会返回一个空集合
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }

        //将json字符串转换成实体类集合
        List<ProductVo> list = JSONUtil.toList(jsonStr, ProductVo.class);

        return list;
    }

    @Override
    public void register(DeviceDto dto) {
        //1.判断设备标识码是否已存在
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId());
        Device device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备标识码已存在");
        }
        //2.判断设备名称是否已存在
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName());
        device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备名称已存在");
        }
        //3.判断同一位置是否已有一产品
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation());
        device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备已存在");
        }
        //4.准备一个密钥
        UUID uuid = UUID.randomUUID();
        String secret = uuid.toString(true);

        //5.设备密钥+设备名称+设备标识码+产品id

        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());

        AuthInfo authInfobody = new AuthInfo();
        authInfobody.withSecret(secret);
        body.setAuthInfo(authInfobody);

        request.setBody(body);
        AddDeviceResponse response = ioTDAClient.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("请求华为云失败");
        }
        //6.返回一个设备在物联网平台的id
        String iotId = response.getDeviceId();

        //7.封装device对象实体类， 包括参数里设置信息，以及设备的物联网id+密钥
        device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(iotId);
        device.setSecret(secret);
        //8.保存到数据库里
        save(device);
    }

    @Override
    public DeviceDetailVo getByIotId(String iotId) {
        //根据id去数据库表中查询设备信息
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        Device device = getOne(wrapper);
        //根据iotId取华为云获取设备状态和激活时间
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = ioTDAClient.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("请求华为云失败");
        }
        String status = response.getStatus();
        String activeTime = response.getActiveTime();
        LocalDateTime activeDate = null;
        if (StringUtils.isNotEmpty(activeTime)) {
            activeDate = LocalDateTime.parse(activeTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            //将0时区，转换为东八区的时间
            activeDate = activeDate.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
//            activeDate2 = activeDate2.plusHours(8);
        }
        DeviceDetailVo detailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, detailVo);

        Date createTime = device.getCreateTime();
        //将createTime转换为LocalDateTime
        LocalDateTime createDate = createTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        detailVo.setCreateTime(createDate);
        detailVo.setDeviceStatus(status);
        detailVo.setActiveTime(activeDate);
        return detailVo;
    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        //根据iotId从华为云 查询所有的设备的物模型数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("请求华为云失败");
        }
        DeviceShadowProperties reported = response.getShadow().get(0).getReported();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime1 = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        //用一行代码将eventDate，从0时区转换为东八区
        LocalDateTime eventTime = eventTime1.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

        List<DeviceReportDataVo> deviceReportDataVos = new ArrayList<>();
        //将获取到的物模型列表转换为map键值对类型
        Map<String, Object> properties = (Map<String, Object>) reported.getProperties();
        properties.forEach((prop, value) ->
        {
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(prop);
            vo.setValue(value);
            vo.setEventTime(eventTime);
            //将查询到的每个vo对象添加list集合中
            deviceReportDataVos.add(vo);
        });
        return deviceReportDataVos;
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        //向华为云发送请求，获取产品的详情
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = ioTDAClient.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            throw  new BaseException("查询产品详情api,请求失败");
        }
        return response.getServiceCapabilities();
    }
}
